package com.YHVision.qiuzhike.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.YHVision.qiuzhike.annotation.AuthCheck;
import com.YHVision.qiuzhike.common.BaseResponse;
import com.YHVision.qiuzhike.common.DeleteRequest;
import com.YHVision.qiuzhike.common.ErrorCode;
import com.YHVision.qiuzhike.common.ResultUtils;
import com.YHVision.qiuzhike.constant.UserConstant;
import com.YHVision.qiuzhike.exception.BusinessException;
import com.YHVision.qiuzhike.exception.ThrowUtils;
import com.YHVision.qiuzhike.model.dto.userCompany.UserCompanyAddRequest;
import com.YHVision.qiuzhike.model.dto.userCompany.UserCompanyEditRequest;
import com.YHVision.qiuzhike.model.dto.userCompany.UserCompanyQueryRequest;
import com.YHVision.qiuzhike.model.dto.userCompany.UserCompanyUpdateRequest;
import com.YHVision.qiuzhike.model.entity.UserCompany;
import com.YHVision.qiuzhike.model.entity.User;
import com.YHVision.qiuzhike.model.vo.UserCompanyVO;
import com.YHVision.qiuzhike.service.UserCompanyService;
import com.YHVision.qiuzhike.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户企业关联接口
 *
 * @author <a href="">YHVision-小y</a>
 * @from <a href="todo">爱编程学习圈</a>
 */
@RestController
@RequestMapping("/userCompany")
@Slf4j
public class UserCompanyController {

    @Resource
    private UserCompanyService userCompanyService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建用户企业关联
     *
     * @param userCompanyAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUserCompany(@RequestBody UserCompanyAddRequest userCompanyAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userCompanyAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        UserCompany userCompany = new UserCompany();
        BeanUtils.copyProperties(userCompanyAddRequest, userCompany);
        // 数据校验
        userCompanyService.validUserCompany(userCompany, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        userCompany.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = userCompanyService.save(userCompany);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newUserCompanyId = userCompany.getId();
        return ResultUtils.success(newUserCompanyId);
    }

    /**
     * 删除用户企业关联
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserCompany(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserCompany oldUserCompany = userCompanyService.getById(id);
        ThrowUtils.throwIf(oldUserCompany == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldUserCompany.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userCompanyService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新用户企业关联（仅管理员可用）
     *
     * @param userCompanyUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUserCompany(@RequestBody UserCompanyUpdateRequest userCompanyUpdateRequest) {
        if (userCompanyUpdateRequest == null || userCompanyUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        UserCompany userCompany = new UserCompany();
        BeanUtils.copyProperties(userCompanyUpdateRequest, userCompany);
        // 数据校验
        userCompanyService.validUserCompany(userCompany, false);
        // 判断是否存在
        long id = userCompanyUpdateRequest.getId();
        UserCompany oldUserCompany = userCompanyService.getById(id);
        ThrowUtils.throwIf(oldUserCompany == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = userCompanyService.updateById(userCompany);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户企业关联（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserCompanyVO> getUserCompanyVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        UserCompany userCompany = userCompanyService.getById(id);
        ThrowUtils.throwIf(userCompany == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(userCompanyService.getUserCompanyVO(userCompany, request));
    }

    /**
     * 分页获取用户企业关联列表（仅管理员可用）
     *
     * @param userCompanyQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @SaCheckRole(UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserCompany>> listUserCompanyByPage(@RequestBody UserCompanyQueryRequest userCompanyQueryRequest) {
        long current = userCompanyQueryRequest.getCurrent();
        long size = userCompanyQueryRequest.getPageSize();
        // 查询数据库
        Page<UserCompany> userCompanyPage = userCompanyService.page(new Page<>(current, size),
                userCompanyService.getQueryWrapper(userCompanyQueryRequest));
        return ResultUtils.success(userCompanyPage);
    }

    /**
     * 分页获取用户企业关联列表（封装类）
     *
     * @param userCompanyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserCompanyVO>> listUserCompanyVOByPage(@RequestBody UserCompanyQueryRequest userCompanyQueryRequest,
                                                               HttpServletRequest request) {
        long current = userCompanyQueryRequest.getCurrent();
        long size = userCompanyQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserCompany> userCompanyPage = userCompanyService.page(new Page<>(current, size),
                userCompanyService.getQueryWrapper(userCompanyQueryRequest));
        // 获取封装类
        return ResultUtils.success(userCompanyService.getUserCompanyVOPage(userCompanyPage, request));
    }

    /**
     * 分页获取当前登录用户创建的用户企业关联列表
     *
     * @param userCompanyQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<UserCompanyVO>> listMyUserCompanyVOByPage(@RequestBody UserCompanyQueryRequest userCompanyQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(userCompanyQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        userCompanyQueryRequest.setUserId(loginUser.getId());
        long current = userCompanyQueryRequest.getCurrent();
        long size = userCompanyQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserCompany> userCompanyPage = userCompanyService.page(new Page<>(current, size),
                userCompanyService.getQueryWrapper(userCompanyQueryRequest));
        // 获取封装类
        return ResultUtils.success(userCompanyService.getUserCompanyVOPage(userCompanyPage, request));
    }

    /**
     * 编辑用户企业关联（给用户使用）
     *
     * @param userCompanyEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editUserCompany(@RequestBody UserCompanyEditRequest userCompanyEditRequest, HttpServletRequest request) {
        if (userCompanyEditRequest == null || userCompanyEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        UserCompany userCompany = new UserCompany();
        BeanUtils.copyProperties(userCompanyEditRequest, userCompany);
        // 数据校验
        userCompanyService.validUserCompany(userCompany, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = userCompanyEditRequest.getId();
        UserCompany oldUserCompany = userCompanyService.getById(id);
        ThrowUtils.throwIf(oldUserCompany == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldUserCompany.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userCompanyService.updateById(userCompany);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
